package com.yimixian.app.util;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.Animator.AnimatorListener;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.view.View;
import android.view.animation.LinearInterpolator;

public class PaoWuXianAnimator {
		
	View v_anim;
	float animStartX, animStartY, xDistance;
	int duration;
	float timeInSecond, v, a;
	ObjectAnimator animX;
		
	public PaoWuXianAnimator(View v_anim, float animStartX, float animStartY, float xDistance, int duration, float v, float a){
		this.v_anim = v_anim;
		this.animStartX = animStartX;
		this.animStartY = animStartY;
		this.xDistance = xDistance;
		this.duration = duration;
		timeInSecond = (duration + 0f) / 1000;
		this.v = v;
		this.a = a;
	}

	public void startAnim(){
		animX = ObjectAnimator.ofFloat(v_anim, "translationX", animStartX, animStartX + xDistance);
		animX.setInterpolator(new LinearInterpolator());
		animX.setDuration(duration);
		animX.addUpdateListener(new AnimatorUpdateListener() {

			@Override
			public void onAnimationUpdate(ValueAnimator animation) {
				float curTime = Float.valueOf(animation.getCurrentPlayTime()) / 1000;
				if(curTime > timeInSecond){
					curTime = timeInSecond;
				}
				float s = v * curTime + 0.5f * a * curTime * curTime;
				v_anim.setY(animStartY + s);

			}
		});

		animX.addListener(new AnimatorListener() {

			private boolean isCancel = false;

			@Override
			public void onAnimationStart(Animator animation) {
				v_anim.setVisibility(View.VISIBLE);
			}

			@Override
			public void onAnimationRepeat(Animator animation) {}

			@Override
			public void onAnimationEnd(Animator animation) {
				v_anim.setVisibility(View.GONE);
				if(paoWuXianEndListener != null && !isCancel)
					paoWuXianEndListener.onEnd();
			}

			@Override
			public void onAnimationCancel(Animator animation) {
				isCancel = true;
			}
		});
		animX.addUpdateListener(new AnimatorUpdateListener() {

			@Override
			public void onAnimationUpdate(ValueAnimator animation) {

			}
		});

		animX.start();
	}

	public void cancel(){
		if(animX != null)
			animX.cancel();
	}


	private onPaoWuXianEndListener paoWuXianEndListener;

	public void setPaoWuXianEndListener(onPaoWuXianEndListener paoWuXianEndListener) {
		this.paoWuXianEndListener = paoWuXianEndListener;
	}

	public interface onPaoWuXianEndListener{
		public void onEnd();
	}

}
